package com.zbkj.front.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.zbkj.common.response.CommonResult;
import com.zbkj.common.token.FrontTokenComponent;
import com.zbkj.common.utils.RequestUtil;
import com.zbkj.common.model.user.User;
import com.zbkj.service.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 移动端token验证拦截器
 * -使用前注意需要一个@Bean手动注解，否则注入无效
 * @author lijie
 */
public class FrontTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private FrontTokenComponent frontTokenComponent;

    @Autowired
    private UserService userService;

    //程序处理之前需要处理的业务
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //设置编码
        response.setCharacterEncoding("UTF-8");

        //判断-token是否为空
        String token = frontTokenComponent.getToken(request);
        if(token == null || token.isEmpty()){
            //判断路由，部分路由不管用户是否登录都可以访问
            boolean result = frontTokenComponent.checkRouter(RequestUtil.getUri(request));
            if(result){
                return true;
            }
            response.getWriter().write(JSONObject.toJSONString(CommonResult.unauthorized()));
            return false;
        }

        //判断-token是否过期
        Boolean result = frontTokenComponent.check(token, request);
        if(!result){
            response.getWriter().write(JSONObject.toJSONString(CommonResult.unauthorized()));
            return false;
        }

        //判断-是否终身免费
        User user = userService.getInfoException();
        if(user.getIsLifelong()){
            return true;
        }

        //判断-账户积分
        boolean loginIfIntegral = frontTokenComponent.loginIfIntegral(RequestUtil.getUri(request));
        if(user.getIntegral() <= 0 && !loginIfIntegral){
            response.getWriter().write(JSONObject.toJSONString(CommonResult.notBalance()));
            return false;
        }
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }

}
